package com.ruoyi.zhjd.common.util;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ZhjdIotUtils
 * @Description 养护基地物联设备工具类
 * @author linhuawei
 * @since 2023-06-05
 */
public class ZhjdIotUtils {

    // 试验数据
    public static final String DATA_TYPE_TEST = "A4";

    // 结果数据
    public static final String DATA_TYPE_RES = "A7";

    // 试验结果过程数据
    public static final String DATA_TYPE_PROCESS = "A6";

    // 无效数据
    public static final String FLAG_INVALID_DATA = "00";

    // 试验数据
    public static final String FLAG_INVALID_TEST = "01";

    // 沥青低温延伸度试验仪
    public static final String ASPHALT_LOW_TEMPERATURE_ELONGATION = "1";

    // 沥青针入度仪
    public static final String ASPHALT_PENETROMETER = "2";

    // 沥青软化点试验仪
    public static final String ASPHALT_SOFTENING_POINT = "3";

    // 燃烧法沥青含量测定仪（燃烧炉）
    public static final String ASPHALT_COMBUSTION_FURNACE = "4";

    // 马歇尔稳定度测定仪
    public static final String MARSHALL_STABILITY_NEW = "5";

    /**
     * @Title bytesToHex
     * @Description byte数值转16进制字符串
     * @param bytes 需要处理的数据
     * @param start 开始位置
     * @param end   结束位置
     * @return 16进制字符串
     */
    public static String bytesToHex(byte[] bytes, int start, int end) {
        StringBuffer sbf = new StringBuffer();
        for (int i = start; i < end; i++) {
            sbf.append(byteToHex(bytes[i]));
        }
        return sbf.toString();
    }

    /**
     * @Title bytesToHex
     * @Description byte数值转16进制字符串
     * @param bytes 需要处理的数据
     * @return 16进制字符串
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer sbf = new StringBuffer();
        for (byte byt : bytes) {
            sbf.append(byteToHex(byt));
        }
        return sbf.toString();
    }

    /**
     * @Title byteToHex
     * @Description byte转16进制字符串
     * @param byt 需要处理的数据
     * @return 16进制字符串
     */
    public static String byteToHex(byte byt) {
        String hex = Integer.toHexString(byt & 0xff);
        return 1 == hex.length() ? "0" + hex : hex;
    }

    /**
     * @Title bytesToLong
     * @Description byte数组，转换为长整型
     * @param bytes byte数组
     * @param start 开始位置
     * @param end   结束位置
     * @return 转化结果
     */
    public static long bytesToLong(byte[] bytes, int start, int end) {
        long value = 0;
        int length = end - start;
        for (int i = start; i < end; i++) {
            long temp = (long) bytes[i] & 0xff;
            long temp1 = (length - i + start - 1) * 8L;
            value |= (temp << temp1);
        }
        return value;
    }

    /**
     * @Title trimPrefixZero
     * @Description 处理字符串前缀填补的0
     * @param str 需要处理的字符串
     * @return 处理后的字符串
     */
    public static String trimPrefixZero(String str) {
        if (null != str) {
            while (str.startsWith("0")) {
                str = str.substring(1);
            }
        }
        return str;
    }

    /**
     * @Title crcForMmit
     * @Description mmit协议获取crc校验码
     * @param bytes 需要校验的数据
     * @param start 开始位
     * @param end   结束位
     * @return 校验码
     */
    public static int crcForMmit(byte[] bytes, int start, int end) {
        int crc = 0x00;
        int polynomial = 0x1021;
        for (int i = start; i < end; i++) {
            byte b = bytes[i];
            for (int j = 0; j < 8; j++) {
                boolean bit = ((b >> (7 - j) & 1) == 1);
                boolean c15 = ((crc >> 15 & 1) == 1);
                crc <<= 1;
                if (c15 ^ bit)
                    crc ^= polynomial;
            }
        }
        crc &= 0xffff;
        return crc;
    }

    /**
     * @Title hexToBytes
     * @Description 16进制字符串转byte数组
     * @param hex 需要处理的字符串
     * @return byte数组
     */
    public static byte[] hexToBytes(String hex) {
        if (null == hex || 2 > hex.length()) {
            return null;
        }

        int len = hex.length() / 2;
        byte[] bytes = new byte[len];
        for (int i = 0; i < len; i++) {
            bytes[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
        }
        return bytes;
    }

    /**
     * 十六进制转10进制，高八位在前，不含（0x）
     * @param highOctet
     * @param lowerOctet
     * @return
     */
    public static BigDecimal hexToDecimalism(String highOctet, String lowerOctet){
        Integer highOctetNum = Integer.parseInt(highOctet,16);
        Integer lowerOctetNum = Integer.parseInt(lowerOctet,16);
        return new BigDecimal("" + highOctetNum + "." + lowerOctetNum);
    }

    /**
     * 解析试验数据
     * @param originData
     * @return
     */
    public static List<String> analyzeExperimentalData(String originData){
        List<String> dataList = new ArrayList<>();
        //如果长度大于2，则进行解析
        while (originData.length() > 2) {
            String data = originData.substring(0,2);
            dataList.add(data);
            originData = originData.substring(2,originData.length());
        }
        return dataList;
    }


    /**
     * 根据小数位数进行截取
     * @param data
     * @return
     */
    public static BigDecimal subByDecimalPlaces(Integer x,String data){
        return new BigDecimal(data.substring(0, data.length() - x) + "." + data.substring(data.length() - x,data.length()));
    }

    /**
     * 解析数据
     * @param req
     * @return
     */
    public static String dataParsing(HttpServletRequest req){
        ServletInputStream in = null;
        ByteArrayOutputStream out = null;
        byte[] bytes = null;
        try {
            in = req.getInputStream();
            out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            bytes = out.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        if (null != bytes) {
            return ZhjdIotUtils.bytesToHex(bytes).toUpperCase();
        } else {
            return null;
        }
    }
}
